package com.gw.smscheck.timer;

import com.gw.smscheck.entity.business.positionInfo.PositionInfo;
import com.gw.smscheck.entity.business.positionInfo.PositionTrajectory;
import com.gw.smscheck.service.business.positionInfo.PositionInfoService;
import com.gw.smscheck.service.business.positionInfo.PositionNowService;
import com.gw.smscheck.util.DoubleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 位置信息创建器
 * 每分钟一条数据
 */
@Component
public class PositionCreater {

    @Autowired
    PositionInfoService positionInfoService;

    @Autowired
    PositionNowService positionNowService;

    /**
     * 基础位置信息创建器（随机移动）
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Scheduled(cron = "0/10 * * * * ?")
    public void basePositionCreater(){
        //获取上一条数据
        PositionTrajectory newPosition = positionInfoService.getNewByPhone("18484842424");
        System.out.println(newPosition.getLng());

        //基础数据
        PositionInfo temp = new PositionInfo();
        temp.setPhoneNum(newPosition.getPhoneNum());
        temp.setTime(timeAddMinute(newPosition.getLastTime()));
        //动态生成经纬度
        Double nowLng = DoubleUtil.getRandom(newPosition.getLng(),10,8,0.001);
        Double nowLat = DoubleUtil.getRandom(newPosition.getLat(),10,8,0.001);
        temp.setLng(nowLng);
        temp.setLat(nowLat);
        positionInfoService.add(temp);//添加日志记录
        //如果上一个点和当前这个点的位置一致，则修改上一个点的last_time为当前时间点
        //否则新增一条数据
        if(newPosition.getLng().equals(nowLng) && newPosition.getLat().equals(nowLat)){
            System.out.println("修改");
            newPosition.setLastTime(temp.getTime());
            newPosition.setLat(nowLat);
            newPosition.setLng(nowLng);
            positionInfoService.updateLastTimeForTrajectory(newPosition);
        }else{
            System.out.println("添加");
            positionInfoService.addTrajectory(temp);
        }
        //添加最新日志，存在即更新，反之插入
        positionNowService.updataInsert(temp);
    }


//    public static void main(String args[]){
//        PositionCreater p = new PositionCreater();
//        String time = "201810300001";
//        System.out.println(p.timeAddMinute(time));
//    }



    /**
     *
     *
     * @return
     */
    private String timeAddMinute(String sourceTime){
        String resultStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        try {
            Date time = sdf.parse(sourceTime);
            Calendar c = Calendar.getInstance();
            c.setTime(time);
            c.add(Calendar.MINUTE,1);
            resultStr = sdf.format(c.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultStr;
    }

}
